/**
 * 参考文档：https://juejin.cn/post/6844903985338400782
 * hooks写在函数的最外层，不能写在ifelse等条件语句当中，来确保hooks的执行顺序一致。
 
 */
import React, { useState, memo, useMemo, useCallback } from 'react';
import './index.less';
// import { useParams } from 'react-router-dom';
import { inject, observer } from 'mobx-react';
import { Button } from 'antd-mobile';
import Title from '../../components/title';
import StateCom from './state';
import ReducerCom from './reducer';
import EffectCom from './effect';
import ContextCom from './context';
import LayoutEffectCom from './layouteffect';
import UserefCom from './useref';
import ForwardRefCom from './forwardref';
import DirectiveSelfCom from './directiveSelf';

const StateComn = memo(StateCom); // 将子组间使用memo进行处理
function HooksDemo(props: any) {
  console.log('hooks-demo proops', props);

  // const routeParams:any = useParams(); //useParams()可获取路由传过来的参数
  const routeParams: any = props.match.params; // props.match.params可获取路由传过来的参数,作用等同于useParams()
  const routeTitle = routeParams.title;

  /**
   *  前提，子组件依赖父组件的state
   *  父组件每次有state数据改变时，都会重新渲染子组件，引起较大的渲染开销，可以使用memo，useMemo,useCallback来解决
   *  1 将子组间使用memo进行处理
   *  2 对传给子组件的数据和方法进行处理 用useMemo处理state数据，用useCallback处理方法，
   *    其依赖都是num,若不依赖任何数据，子组件仍会被重新渲染
   */
  const [num, setNum] = useState(1);
  const data = useMemo(() => num, [num]);
  const addClick = useCallback(() => {
    setNum(() => {
      const newNum = num + 1;
      console.log('new num ===', newNum);
      return newNum;
    });
  }, [num]);

  const [name, setName] = useState('ming');
  function changeName() {
    setName('tian');
    setNum(num + 1);
  }
  console.log(6666, name, num);
  return (
    <div className='hooks-demo'>
      <Button onClick={() => changeName()}>{name}</Button>
      <Title title={routeTitle} left={true} />
      <p>useState</p>
      <StateComn data={data} addClick={addClick} />
      <p>useReducer</p>
      <ReducerCom />
      <p>useEffect</p>
      <EffectCom />
      <p>useContext</p>
      <ContextCom />
      <p>useLayoutEffect</p>
      <LayoutEffectCom />
      <p>useRef</p>
      <UserefCom />
      <p>forwardRef</p>
      <ForwardRefCom />
      <p>自定义hook</p>
      <DirectiveSelfCom />
    </div>
  );
}
export default inject('languageStore', 'rtlStore')(observer(HooksDemo));
